package com.im.utils.Redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * Redis ID 生成器
 */
@Component
public class RedisIdGenerator {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String GROUP_ID_KEY = "im:group_id:create"; // Redis Key
    private static final String USER_ID_KEY = "im:user_id:create";   // Redis Key
    private static final String SESSION_ID_KEY = "im:session_id:create"; // Redis Key
    private static final Random RANDOM = new Random();

    /**
     * 生成 8-10 位唯一群组 ID
     */
    public int generateGroupId() {
        long increment = redisTemplate.opsForValue().increment(GROUP_ID_KEY);
        int suffix = RANDOM.nextInt(90) + 10; // 生成两位随机数
        String groupId = (10000000 + increment) + String.valueOf(suffix); // 确保最小 8 位
        return Integer.parseInt(groupId.length() > 10 ? groupId.substring(0, 10) : groupId);
    }

    /**
     * 生成 9 位唯一用户 ID
     */
    public int generateUserId() {
        long userId = redisTemplate.opsForValue().increment(USER_ID_KEY, 1);
        return (int) (100000000L + userId); // 确保 ID 9 位
    }

    /**
     * 生成 18 位唯一会话 ID
     */
    public long generateSessionId() {
        long timestamp = System.currentTimeMillis(); // 当前时间戳
        long increment = redisTemplate.opsForValue().increment(SESSION_ID_KEY, 1); // Redis 递增值
        String sessionIdStr = timestamp + String.format("%04d", increment % 10000); // 取后4位保证长度
        return Long.parseLong(sessionIdStr.length() > 18 ? sessionIdStr.substring(0, 18) : sessionIdStr);
    }
}
